package com.xy.mainp.novel.widget;


import android.content.Context;
import android.support.v4.app.Fragment;

import com.xy.debug.LogUtils;
import com.xy.mainp.model.biqu.BiquCategoryEntity;
import com.xy.mainp.novel.fragment.HasReadFragment;
import com.xy.mainp.novel.fragment.mybook.MyBookFragment;
import com.xy.mainp.novel.fragment.NovelEndFragment;
import com.xy.mainp.novel.fragment.home.NovelHomeFragment;
import com.xy.mainp.novel.fragment.NovelShowFragment;
import com.xy.mainp.utils.NetRequestUtils;
import com.xy.manager.MsgManager;
import com.xy.net.OkHttpUtils;

import java.util.List;

import okhttp3.Request;

/**
 * Created by John on 2016/11/28.
 */

public class NovelFragmentHelper {

    private  BiquCategoryEntity entity;
    private  NetDataListener mListener;
    private static Context mContext;
    private static NovelFragmentHelper instance;
    private NovelFragmentHelper(){

    }

     public static NovelFragmentHelper getInstance(Context context){
         if (instance == null){
             instance = new NovelFragmentHelper();
             mContext = context;
         }
         return instance;
     }


    public  void setNetDateListener(NetDataListener listener){
        mListener = listener;
    }

    public  Fragment getFragment(List<BiquCategoryEntity> entities,int position){
        entity = entities.get(position);
        if ("首页".equalsIgnoreCase(entity.getName())){
            return new NovelHomeFragment(entity.getUrl());
        }else if ("我的书架".equalsIgnoreCase(entity.getName())){
            return new MyBookFragment(entity.getUrl());
        }else if ("完本小说".equalsIgnoreCase(entity.getName())){
            return new NovelEndFragment(entity.getUrl());
        }else if ("阅读记录".equalsIgnoreCase(entity.getName())){
            return new HasReadFragment();
        }else {
            return new NovelShowFragment(entity);
        }
    }

    public  void LoadNetData(String url){
        final MsgManager msgManager = new MsgManager(mContext);
        msgManager.showLoading(true);
        NetRequestUtils.getInstance(mContext).getBiQuData(url, new OkHttpUtils.ResultCallBack<String>() {
            @Override
            public void onError(Request request, Exception e) {
                msgManager.showLoading(false);
                msgManager.showToastMsg(e.getMessage());
            }

            @Override
            public void onResult(final String result) {
                msgManager.showLoading(false);
                if (mListener != null){
                    new Thread(new Runnable(){
                        @Override
                        public void run() {
                            mListener.deal(result);
                        }
                    }).start();
                }else {
                    LogUtils.e("netDataListner is null");
                }
            }
        });
    }


    public interface NetDataListener{
        void deal(String result);
    }
}
